/**   
* @{#} Filter.java Create on 2013-6-22 下午4:20:20   
*   
* Copyright (c) 2012 by Baidu.   
*/
package objtable.algm;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import objtable.core.ScriptEnv;
import objtable.core.TableCenter;
import objtable.struct.Row;

/**   
* @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>  
* @version 1.0   
* 主要是过滤数据的目的，相当于SQL中的where
*/

public class FilterBy implements Algm1Row {
	private String express;

	/**
	 * @param simpleExpress 简单表达式，返回结果一定是true或者false
	 * 比如：a>1 && b < 2
	 */
	public FilterBy(String simpleExpress) {
		this.express = simpleExpress;
	}

	public List<? extends Row> execute(List<? extends Row> rows) {
		List<Row> result = new ArrayList<Row>(rows.size());
		if (rows.size() > 0) {
			String[] fields = TableCenter.getTable(rows.get(0).getTableName())
					.getFields();
			String exp = wrapExpressWithFor(fields, "obj.");
			HashMap<String, Object> cmp = ScriptEnv.cloneComputeObj();
			cmp.put("objs", rows);
			cmp.put("ret", result);
			ScriptEnv.execute(exp, cmp);
			return result;
		}
		return result;
	}

	private String wrapExpressWithFor(String[] fields, String prefix) {
		String result = ScriptEnv.replaceFieldsWithPrefix(express, fields,
				prefix);
		result = "size=objs.size();for(i=0;i<size;i++){obj=objs.get(i);if("
				+ result + "){ret.add(obj);}}";
		return result;
	}
}
